<template>
  <div>
    <el-form slot:default label-width="100px" ref="form" class="kylin-form">
      <el-form-item :label="$t('file')" prop="file">
        <el-upload
          ref="upload"
          :headers="header"
          :action="action"
          :file-list="fileList"
          :auto-upload="false"
          accept=".xls"
          :on-success="handleSuccess"
          :on-error="handleError"
          :on-remove="handleFileChange"
          :on-change="handleFileChange"
        >
          <el-button slot="trigger" size="small" class="kylin-button">{{
            $t("configure.click_select_file")
          }}</el-button>
          <div
            slot="tip"
            :class="
              showfileMessage
                ? 'el-upload__tip el-form-item__error'
                : 'el-upload__tip'
            "
            style="position: unset"
          >
            只能上传xls文件<span v-if="showfileMessage">,文件是必填项</span>
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">{{ $t("cancel") }}</el-button>
      <el-button class="kylin-button" @click="handleOk">{{
        $t("upload")
      }}</el-button>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      fileList: [],
      showfileMessage: false,
      action: "/api/hosts/create",
      header: { authToken: getToken() },
    };
  },
  methods: {
    handleCancel() {
      this.fileList = [];
      this.$emit("click");
    },
    handleSuccess(res) {
      if (res.code == 0) {
        this.$message({
          type: "success",
          message: res.message,
        });
      } else {
        this.$message({
          type: "error",
          message: res.message,
        });
      }
      this.fileList = [];

      this.$emit("click");
    },
    handleError(res) {
      this.fileList = [];
      this.$message({
        type: "error",
        message: res.message,
      });
      this.$emit("click");
    },
    handleOk() {
      if (this.fileList.length > 0) {
        this.$refs.upload.submit();
      } else {
        this.showfileMessage = true;
      }
    },
    handleFileChange(file, fileList) {
      if (fileList.length == 0) {
        this.showfileMessage = true;
      } else {
        if (fileList.length > 1) {
          this.fileList = fileList.slice(-1);
        } else {
          this.fileList = fileList;
        }
        this.showfileMessage = false;
      }
    },
  },
};
</script>

<style>
</style>